package com.xl.basic.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import com.xl.basic.annotation.LogIgnored;
import com.xl.basic.annotation.LoginIgnored;
import com.xl.basic.entity.Result;
import com.xl.basic.entity.ResultEnums;
import com.xl.basic.utils.FileUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 钟勇
 * Create in 2023/8/18 16:22
 */
@Tag(name = "文件上传")
@RestController
@RequestMapping("/File")
@LoginIgnored
@LogIgnored
@RequiredArgsConstructor
public class FileController {

    private final WxMpService wxMpService;

    @Operation(summary = "保存微信图片")
    @PostMapping(value = "/uploadWxImage")
    public Result<List<String>> uploadWxImage(@NotBlank(message = "微信图片ID不能为空") String serverIds) {
        List<String> serverIdList = ListUtil.of(serverIds.split(","));
        List<String> urlList = new ArrayList<>();

        for (String serverId : serverIdList) {
            try {
                File file = wxMpService.getMaterialService().mediaDownload(serverId);
                Result<FileUtils.UploadInfo> uploadInfoRes = FileUtils.getUploadInfo("jpg");
                if (uploadInfoRes.isErr()) {
                    return uploadInfoRes.create();
                }

                FileUtils.UploadInfo uploadInfo = uploadInfoRes.getResult();
                FileUtil.writeBytes(FileUtil.readBytes(file), uploadInfo.getUploadDir());
                urlList.add(uploadInfo.getVisitPath());
            } catch (WxErrorException e) {
                return ResultEnums.Exception.getResult(e.toString());
            }
        }

        if (urlList.isEmpty()) {
            return ResultEnums.BusinessError.getResult("图片保存失败");
        }

        return ResultEnums.Success.getListResult(urlList);


    }

    @Operation(summary = "图片上传")
    @PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadImage(@RequestPart("file") MultipartFile file) {
        return FileUtils.uploadImage(file);
    }

    @Operation(summary = "文件上传")
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadFile(@RequestPart("file") MultipartFile file) {
        return FileUtils.uploadFile(file);
    }
}
